/**
 * @function autoList查询表单数据函数
 * @param {*} that 
 * @param {*} params 
 * @param {*} manageAPI 
 * @param {*} storage 
 * @param {*} tools 
 */
export async function queryDataInfo(that, params, manageAPI, storage, tools) {

    //查询用户信息
    var userInfo = storage.getStore('cur_user');

    //获取流程相关数据
    var result = await queryWFlowDataInfo(that, userInfo, params, manageAPI);

    //获取表单信息
    var tableInfo = await manageAPI.queryTableData(`onl_cgform_head`, that.code);

    //获取表单名称
    var tableName = tableInfo.table_name;

    //根据返回结果进行相应处理
    if (result == null) {
        try {
            //查询数据
            var res = null;
            //通过RestAPI查询数据
            res = await manageAPI.queryTableDataByParam(tableName, userInfo['username'], userInfo['realname'], 0, 100000, params);
            //如果数据为空，则重新查询
            if (res != null && res.result.total == 0 && res.result.records.length == 0) {
                res = await manageAPI.getAction(`${that.url.getData}${that.code}`, params);
            }
            //对返回的数据进行处理
            await handleDataInfo(that, res, storage, tools);
        } catch (error) {
            console.log(error);
        }
    } else {
        try {
            if (Number(result.total) > 0) {
                that.table.pagination.total = Number(result.total);
                that.table.dataSource = result.records;
            } else {
                that.table.pagination.total = 0;
                that.table.dataSource = [];
            }
            that.table.loading = false;
        } catch (error) {
            console.log(error);
        }
    }
}

/**
 * @function 查询流程相关数据函数
 * @param {*} that 
 * @param {*} res 
 * @param {*} storage 
 * @param {*} tools 
 */
export async function queryWFlowDataInfo(that, userInfo, params, manageAPI) {

    //定义返回结果
    var result = null;

    //定义Code函数配置
    var codeFunc = {
        '0b511f234f3847baa50106a14fff6215': 'queryProcessLogToApproved',
        'dae6cc0e7a7f4b7e9dc0fc36757fdc96': 'queryProcessLogHisApproved',
        'd11901bc44f24a66b25b37a7a04c611e': 'queryProcessLogInfApproved'
    }

    //定义Description函数配置
    var descFunc = {
        '流程审批日志表': 'queryProcessLogToApproved',
        '流程审批日志历史表': 'queryProcessLogHisApproved',
        '流程审批知会表': 'queryProcessLogInfApproved'
    }

    if (Object.keys(codeFunc).includes(that.code) && Object.keys(descFunc).includes(that.description)) {
        result = await manageAPI[codeFunc[that.code]](
            userInfo['username'],
            userInfo['realname'],
            params
        );
    }

    return result;
}

/**
 * @function 处理数据函数
 * @param {*} that 
 * @param {*} res 
 * @param {*} storage 
 * @param {*} tools 
 */
export async function handleDataInfo(that, res, storage = window.storage, tools = window.tools) {

    if (res.success) {
        //获取查询结果
        var result = res.result;
        //查询用户信息
        var userInfo = storage.getStore('cur_user');
        //如果返回数据大于零，则进行筛选
        if (Number(result.total) > 0) {
            //获取分页数据总数
            that.table.pagination.total = Number(res.result.total);

            res.result.records = window.__.filter(
                res.result.records,
                function(item) {

                    //如果是在团队管理界面，则只有团队负责人和成员能查看团队列表
                    if (
                        'leader' in item &&
                        that.code == '079c6dd6140c4b269e9bf8601deef901'
                    ) {
                        var members = tools.deNull(item['members']).split(',');

                        var flag =
                            item['leader'] == userInfo['username'] ||
                            item['leader'] == userInfo['realname'];

                        var mflag =
                            members.includes(userInfo['username']) ||
                            members.includes(userInfo['realname']);

                        flag = flag || mflag;

                        return flag;
                    }

                    //其他数据，只能数据创建人可以查看数据
                    if (
                        'create_by' in item &&
                        that.code != 'bd3d13e4fa5c4b0d91d589cd554397bd'
                    ) {
                        return (
                            item['create_by'] == userInfo['username'] ||
                            item['create_by'] == userInfo['realname']
                        );
                    } else if (
                        'employee' in item &&
                        that.code != 'bd3d13e4fa5c4b0d91d589cd554397bd'
                    ) {
                        return (
                            item['employee'] == userInfo['username'] ||
                            item['employee'] == userInfo['realname']
                        );
                    } else if (
                        'proposer' in item &&
                        that.code == '933e21cf445440abb8cfdae366082a62'
                    ) {
                        //外出页面使用
                        return (
                            item['proposer'] == userInfo['username'] ||
                            item['proposer'] == userInfo['realname']
                        );
                    } else {
                        return true;
                    }
                }
            );
            //分页条件
            that.pagination.total = res.result.records.total;
            //对返回数据进行过滤,只展示创建人为自己的数据
            that.table.dataSource = res.result.records;
        } else {
            that.table.pagination.total = 0;
            that.table.dataSource = [];
        }
    } else {
        that.$message.warning(res.message);
    }
    //隐藏加载状态显示
    that.table.loading = false;
}

/**
 * @function 初始化表单函数
 */
export async function initAutoList(that, manageAPI, tools, dictSelectUtil) {

    //显示加载状态
    that.table.loading = true;

    //设置code属性
    if (!that.$route.params.code) {
        that.queryCode();
    } else if (tools.isNull(that.code)) {
        that.code = that.$route.params.code;
    }

    //发送请求，查询字段信息
    var res = await manageAPI.getAction(`${that.url.getColumns}${that.code}`);

    if (res.success) {
        that.dictOptions = res.result.dictOptions;
        that.formTemplate = res.result.formTemplate;
        that.description = res.result.description;
        that.currentTableName = res.result.currentTableName;

        that.initCgButtonList(res.result.cgButtonList);
        that.initCgEnhanceJs(res.result.enhanceJs);
        that.initButtonSwitch(res.result.hideColumns);

        //遍历当前字段
        let currColumns = res.result.columns;
        for (let a = 0; a < currColumns.length; a++) {
            if (currColumns[a].customRender) {
                let dictCode = currColumns[a].customRender;
                currColumns[a].customRender = (text) => {
                    return dictSelectUtil.filterMultiDictText(that.dictOptions[dictCode], text);
                };
            }
        }

        //新增操作字段
        currColumns.push(that.actionColumn);
        //表单columns设置
        that.table.columns = [...currColumns];

        //去掉展示content内容列，通过点击+按钮展示
        that.table.columns = window.__.filter(that.table.columns, (item) => {
            return item.dataIndex != 'content';
        });

        that.hasBpmStatusFilter();
        that.loadData();

        await that.initQueryInfo();

    } else {
        that.$message.warning(res.message);
    }

}

/**
 * @function 初始化查询信息
 */
export async function initQueryInfo(that, manageAPI) {

    //查询初始化信息
    let res = await manageAPI.getAction(`${that.url.getQueryInfo}${that.code}`);

    //查询成功，则设置查询数据；否则，提示错误信息。
    if (res.success) {
        that.queryInfo = res.result;
    } else {
        that.$message.warning(res.message);
    }

}

/**
 * @function 检查页面code参数
 */
export function queryCode(that) {
    try {
        //获取页面代码
        that.code = window.location.pathname.split('/')[3];
    } catch (e) {
        console.error(e);
    }
}

/**
 * @function 弹框点击OK事件
 */
export function tipHandleOk(that) {
    that.tipConfirmLoading = true;
    setTimeout(() => {
        that.loadData(1);
        that.tipVisible = false;
        that.tipConfirmLoading = false;
    }, 300);
}

/**
 * @function 弹框点击取消事件
 */
export function tipHandleCancel(that) {
    that.loadData(1);
    that.tipVisible = false;
}

/**
 * @function 过滤流程状态函数
 */
export function hasBpmStatusFilter(that) {
    var columnObjs = that.table.columns;
    var columns = [];
    for (var item of columnObjs) {
        columns.push(item.dataIndex);
    }
    if (columns.includes('bpm_status') || columns.includes('BPM_STATUS')) {
        that.hasBpmStatus = true;
    } else {
        that.hasBpmStatus = false;
    }
}

/**
 * @function 弹框处理函数
 */
export function modalOk(that) {
    //获取下拉框选择的值
    let value = that.modelWFlowSelection;

    that.fixedWFlow = window.__.find(that.rights, (item) => {
        return (item['id'] = value);
    });

    //获取流程信息
    let wflow = JSON.stringify(that.fixedWFlow);

    console.log(` 获取流程权责配置 ${value} , fixedWFlow : ${wflow}`);
}

/**
 * @function 获取流程日志函数
 */
export async function processLog(that, storage, manageAPI, business_data_id, record) {

    //获取html信息
    let htmlInfo = storage.getStore(
        `processlog_by_bs_data_id@${business_data_id}`
    );

    if (htmlInfo == null || htmlInfo == '') {
        //获取审批日志信息
        let processLogs = await manageAPI.queryPRLogHistoryByDataID(
            business_data_id
        );

        //遍历审批日志
        processLogs.forEach((item) => {
            htmlInfo =
                htmlInfo +
                `流程名称：${item.process_name} , 流程节点：${
         item.process_station
       } , 处理人： ${item.approve_user} , 审批操作：${item.action} <br/>`;
        });

        record.processlog_html_info = htmlInfo;

        storage.setStore(
            `processlog_by_bs_data_id@${business_data_id}`,
            record,
            10
        );
    }

    //遍历并设置相应html
    that.table.dataSource.forEach((item) => {
        //找到当前选中数据，然后设置相应的html
        if (item.id == business_data_id) {
            item.processlog_html_info = htmlInfo;
        }
    });

    return htmlInfo;
}

/**
 * @function 加载数据函数
 */
export async function loadData(that, arg, handleAPI, manageAPI, storage, tools) {

    //设置页面页码数
    that.table.pagination.current = arg == 1 ? 1 : that.table.pagination.current;

    //查询条件
    let params = that.getQueryParams();

    //如果是审批处理页面，则此处请求数据单独处理
    await handleAPI.queryDataInfo(that, params, manageAPI, storage, tools);

}

/**
 * @function 初始化函数
 */
export async function initComponent(that, manageAPI) {
    //创建页面后，设置选中数据为空
    await that.initAutoList();

    //检查页面code参数
    that.queryCode();

    //设置页面选中信息
    that.table.selectionRows = [];
    that.table.selectedRowKeys = [];

    //查询用户数据，将数据缓存到浏览器缓存
    await manageAPI.queryUserName();
}

/**
 * @function 获取查询条件函数
 */
export function getQueryParams(that, storage, tools) {
    //获取查询条件
    let param = Object.assign({}, that.queryParam, that.isorter);

    //查询用户信息
    var userInfo = storage.getStore('cur_user');

    //需要判断操作时间的页面
    var array = [
        '0b511f234f3847baa50106a14fff6215',
        'dae6cc0e7a7f4b7e9dc0fc36757fdc96',
    ];

    if (array.includes(that.code)) {
        param.column = 'operate_time';
    }

    if (tools.isNull(param.create_by)) {
        param.create_by = userInfo.realname;
    }

    param.pageNo = that.table.pagination.current;
    param.pageSize = that.table.pagination.pageSize;

    return tools.filterObj(param);
}

/**
 * @function 打印表单功能
 */
export async function handlePrintWF(that, storage, manageAPI) {

    //检测是否为单选
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }

    //获取当前用户
    var userInfo = storage.getStore('cur_user');

    //获取此表单，关联的流程业务模块
    var value = await manageAPI.queryTableName();

    //获取选中记录的所属表单名称
    var tableName = value['table_name'];

    //当前被选中记录数据
    var curRow = that.table.selectionRows[0];

    //缓存当前选中数据
    storage.setStore(
        `${tableName}@id=${curRow.id}`,
        JSON.stringify(curRow),
        60000
    );

    //设置跳转URL
    var detailURL = `/workflow/view?table_name=${tableName}&id=${
          curRow.id
        }&user=${userInfo.username}&type=print`;

    //跳转到相应页面
    that.$router.push(detailURL);
}

/**
 * @function 自由流知会功能
 */
export async function handleNotifyWF(that, storage, tools, manageAPI) {

    //检测是否为单选
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }

    //获取当前用户
    var userInfo = storage.getStore('cur_user');

    //获取此表单，关联的流程业务模块
    var value = await manageAPI.queryTableName();

    //获取选中记录的所属表单名称
    var tableName = value['table_name'];

    //当前被选中记录数据
    var curRow = that.table.selectionRows[0];

    //获取知会统计信息
    var countinfo = await manageAPI.queryTableDataByField(
        'v_handling_events',
        'id',
        curRow.id
    );

    //如果流程状态不是待提交，则无法进行自由流程选择
    if (curRow.bpm_status != 4 && curRow.bpm_status != 5) {
        that.$message.warning('此记录尚未审批通过，无法进行知会操作！');
        return false;
    }

    //同一业务数据，同时只能知会一次，本次知会确认完毕后，可以再次知会
    if (tools.deNull(countinfo) != '' && countinfo.length >= 1) {
        that.$confirm_({
            title: '温馨提示',
            content: '此表单业务已进行了知会操作，请不要重复提交!',
        });
        return true;
    }

    //缓存当前选中数据
    storage.setStore(
        `${tableName}@id=${curRow.id}`,
        JSON.stringify(curRow),
        60000
    );

    //设置跳转URL
    var detailURL = `/workflow/view?table_name=${tableName}&id=${
          curRow.id
        }&user=${userInfo.username}&type=notifying`;

    //跳转到相应页面
    that.$router.push(detailURL);
}

/**
 * @function 处理自由流程
 */
export async function handleFreeWF(that, storage, manageAPI) {

    //检测是否为单选
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }

    //获取当前用户
    var userInfo = storage.getStore('cur_user');

    //获取此表单，关联的流程业务模块
    var value = await manageAPI.queryTableName();

    //获取选中记录的所属表单名称
    var tableName = value['table_name'];

    //当前被选中记录数据
    var curRow = that.table.selectionRows[0];

    //如果流程状态不是待提交，则无法进行自由流程选择
    if (curRow.bpm_status != 1) {
        that.$message.warning('此记录已进入流程，无法进行自由流程操作！');
        return false;
    }

    //缓存当前选中数据
    storage.setStore(
        `${tableName}@id=${curRow.id}`,
        JSON.stringify(curRow),
        60000
    );

    //设置跳转URL
    var detailURL = `/workflow/view?table_name=${tableName}&id=${
          curRow.id
        }&user=${userInfo.username}&type=workflowing`;

    //跳转到相应页面
    that.$router.push(detailURL);
}

/**
 * @function 分享详情页面
 */
export async function handleShareWF(that, storage, tools, manageAPI) {

    //检测是否为单选
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }
    //获取当前用户
    var userInfo = storage.getStore('cur_user');

    //获取此表单，关联的流程业务模块
    var value = await manageAPI.queryTableName();

    //获取选中记录的所属表单名称
    var tableName = value['table_name'];

    //当前被选中记录数据
    var curRow = that.table.selectionRows[0];

    //缓存当前选中数据
    storage.setStore(
        `${tableName}@id=${curRow.id}`,
        JSON.stringify(curRow),
        60000
    );

    //设置跳转URL
    var detailURL = `/basewflow/view?table_name=${tableName}&id=${
        curRow.id
    }&user=${userInfo.username}&type=view`;

    //跳转到相应页面
    setTimeout(() => {
        window.open(detailURL + '&flag=timeout', '_blank');
    }, 500);
}

/**
 * @function 查看详情页面
 */
export async function handleDetailWF(that, storage, tools, manageAPI) {

    //检测是否为单选
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }
    //获取当前用户
    var userInfo = storage.getStore('cur_user');

    //获取此表单，关联的流程业务模块
    var value = await manageAPI.queryTableName();

    //获取选中记录的所属表单名称
    var tableName = value['table_name'];

    //当前被选中记录数据
    var curRow = that.table.selectionRows[0];

    //缓存当前选中数据
    storage.setStore(
        `${tableName}@id=${curRow.id}`,
        JSON.stringify(curRow),
        60000
    );

    //设置跳转URL
    var detailURL = `/workflow/view?table_name=${tableName}&id=${
          curRow.id
        }&user=${userInfo.username}`;

    //如果在审批管理菜单下，跳转到详情页面，则应该设置同意驳回确认等按钮
    if (that.code == '0b511f234f3847baa50106a14fff6215') {
        detailURL = `/workflow/view?table_name=${curRow.table_name}&id=${
            curRow.business_data_id
          }&processLogID=${curRow.id}&user=${userInfo.username}&type=workflow`;
    } else if (that.code == 'd11901bc44f24a66b25b37a7a04c611e') {
        detailURL = `/workflow/view?table_name=${curRow.table_name}&id=${
            curRow.business_data_id
          }&processLogID=${curRow.id}&user=${userInfo.username}&type=notify`;
    } else if (that.code == 'dae6cc0e7a7f4b7e9dc0fc36757fdc96') {
        detailURL = `/workflow/view?table_name=${curRow.table_name}&id=${
            curRow.business_data_id
          }&processLogID=${curRow.id}&user=${userInfo.username}&type=history`;
    } else {
        detailURL = `${detailURL}&type=view`;
    }

    //跳转到相应页面
    that.$router.push(detailURL);
}

/**
 * @function 知会确认
 */
export async function handleConfirmWF(that, storage, tools, manageAPI) {

    //返回结果
    var result;
    //获取当前用户
    var userInfo = storage.getStore('cur_user');
    //获取当前时间
    var date = tools.formatDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss');
    //审批动作
    var operation = operation || '知会';
    //审批意见
    var message = message || '已查看此业务流程，知会确认成功！';
    //当前被选中记录数据
    var curRow = that.table.selectionRows[0];
    //流程日志编号
    var processLogID = curRow['id'];
    //定义表单名称
    var tableName = curRow['table_name'];

    //检测是否为单选
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }

    //获取当前审批节点的所有数据
    curRow = await manageAPI.queryProcessLogInfByID(tableName, processLogID);
    //设置本次知会确认创建时间
    curRow['create_time'] = date;

    //如果当前节点的确认信息，已被此节点的所有人员操作完毕，则删除当前知会节点，并修改审批历史日志提交信息
    if (
        tools.deNull(curRow['approve_user']).length >=
        tools.deNull(curRow['employee']).length
    ) {
        //将当前审批日志转为历史日志，并删除当前审批日志中相关信息
        result = await manageAPI.postProcessLogHistory(curRow);
        //删除当前审批节点中的所有记录
        result = await manageAPI.deleteProcessLogInf(tableName, [curRow]);
        that.tipVisible = true;
        that.tipContent = '知会确认成功！';
        return true;
    }

    var employeeList = ',' + tools.deNull(curRow['employee']) + ',';
    var appoveUserList = ',' + tools.deNull(curRow['approve_user']) + ',';

    //检查审批权限，当前用户必须属于操作职员中，才可以进行审批操作
    if (!(
            employeeList.includes(',' + userInfo['username'] + ',') ||
            employeeList.includes(',' + userInfo['realname'] + ',')
        )) {
        that.$message.warning(
            '您不在此知会记录的操作职员列中，无法进行确认操作！'
        );
        return false;
    }

    //已经知会确认过的用户，无法再次知会
    if (
        appoveUserList.includes(',' + userInfo['username'] + ',') ||
        appoveUserList.includes(',' + userInfo['realname'] + ',')
    ) {
        that.$message.warning('您已经在此知会记录中，执行过确认操作了！');
        return false;
    }

    //设置知会确认人员
    curRow['approve_user'] =
        tools.deNull(curRow['approve_user']) +
        (tools.deNull(curRow['approve_user']) == '' ? '' : ',') +
        userInfo['username'];
    //设置操作内容
    curRow['action'] = operation;
    //设置操作时间
    curRow['operate_time'] = date;
    //设置操作意见
    curRow['action_opinion'] =
        tools.deNull(curRow['action_opinion']) +
        (tools.deNull(curRow['action_opinion']) == '' ? '' : '\n\r') +
        `${userInfo['username']}:${message}`;

    //保存当前数据到数据库中
    await manageAPI.patchTableData('PR_LOG_INFORMED', curRow['id'], curRow);

    //如果当前节点的确认信息，已被此节点的所有人员操作完毕，则删除当前知会节点，并修改审批历史日志提交信息
    if (curRow['approve_user'].length >= curRow['employee'].length) {
        //将当前审批日志转为历史日志，并删除当前审批日志中相关信息
        result = await manageAPI.postProcessLogHistory(curRow);
        //删除当前审批节点中的所有记录
        result = await manageAPI.deleteProcessLogInf(tableName, [curRow]);
    }

    that.tipVisible = true;
    that.tipContent = '知会确认成功！';
    that.loadData();

    return result;
}

/**
 * @function 同意审批函数
 */
export async function handleApproveWF(that, storage, tools, manageAPI) {

    //返回结果
    var result;
    //获取当前用户
    var userInfo = storage.getStore('cur_user');
    //获取当前时间
    var date = tools.formatDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss');

    //审批动作
    var operation = operation || '同意';
    //审批意见
    var message = message || '';

    //当前被选中记录数据
    var curRow = that.table.selectionRows[0];

    //流程日志编号
    var processLogID = curRow['id'];
    //业务代码ID
    var bussinessCodeID = curRow['business_data_id'];
    //打印表单名称
    var tableName = curRow['table_name'];

    var processAudit = curRow['process_audit'];

    //定义审批节点信息
    var approveNode = null;

    //检测是否为单选
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }

    //获取当前审批节点的所有数据
    curRow = await manageAPI.queryProcessLogByID(tableName, processLogID);

    //检查审批权限，当前用户必须属于操作职员中，才可以进行审批操作
    if (!(
            curRow['employee'].includes(userInfo['username']) ||
            curRow['employee'].includes(userInfo['realname'])
        )) {
        that.$message.warning(
            '您不在此审批流程记录的操作职员列中，无法进行审批操作！'
        );
        return false;
    }

    //获取关于此表单的所有当前审批日志信息
    let node = await manageAPI.queryProcessLog(tableName, bussinessCodeID);

    //遍历node,设置approve_user，action
    window.__.each(node, function(item) {
        //记录创建时间
        let ctime = item['create_time'];
        //设置审批人员
        item['approve_user'] = userInfo['username'];
        //设置操作类型
        item['action'] = operation;
        //设置操作时间
        item['operate_time'] = date;
        //设置操作意见
        item['action_opinion'] = message;
        //设置创建时间
        item['create_time'] = tools.formatDate(ctime, 'yyyy-MM-dd hh:mm:ss');
    });

    //将当前审批日志转为历史日志，并删除当前审批日志中相关信息
    result = await manageAPI.postProcessLogHistory(node);

    //删除当前审批节点中的所有记录
    result = await manageAPI.deleteProcessLog(tableName, node);

    //第一步，获取此表单，关联的流程业务模块；查询SQL , 获取流程权责中关联业务含有tableName的流程权责
    let rights = await manageAPI.queryBusinessInfo(tableName);

    //选定流程权责
    that.fixedWFlow = rights[0];
    //设置当前流程审批权责
    that.rights = rights;

    //如果流程权责有多个，那么弹出选择框，让用户自己选择一个流程
    if (rights.length > 1 && curRow.business_code != '000000000') {
        that.modelModal = true;
    } else if (rights.length <= 0 && curRow.business_code != '000000000') {
        that.tipVisible = true;
        that.tipContent = '未获取到此业务的流程权责，无法同意审批！';
        return false;
    } else {
        //所有待审核节点
        var allAudit = '';
        //所有待知会节点
        var allNotify = '';
        //当前审核节点
        var curAuditor = processAudit;
        //知会节点数组
        var notifyArray =
            tools.deNull(allNotify) == '' ? '' : allNotify.split(',');

        //如果不是自由流程，则从权责配置中获取待审核人列表，否则，使用自由流程配置的审核人员列表
        if (curRow.business_code != '000000000') {
            try {
                //根据权责配置，获取所有待审核人员列表
                allAudit =
                    ',' +
                    that.fixedWFlow['audit'] +
                    ',' +
                    that.fixedWFlow['approve'] +
                    ',';
                //根据权责配置，获取所有待知会人员列表
                allNotify = that.fixedWFlow['notify'];
                //设置审批节点信息
                approveNode = that.fixedWFlow['approve'];
            } catch (error) {
                that.tipVisible = true;
                that.tipContent = '固化流程设置节点失败，无法进行审批操作！';
                console.log('固化流程设置节点失败 :' + error);
                return false;
            }
        } else {
            try {
                //自由流程配置消息
                let freeNode = JSON.parse(curRow.business_data);
                //根据自由流程配置，获取所有待审核人员列表
                allAudit =
                    ',' + freeNode.audit_node + ',' + freeNode.approve_node + ',';
                //根据自由流程配置，获取所有待知会人员列表
                notifyArray =
                    tools.deNull(freeNode.notify_node) == '' ? [] : [freeNode.notify_node];
                //获取自由流程配置，当前审核节点
                curAuditor = curRow['employee'];
                //设置审批节点信息
                approveNode = freeNode.approve_node;
            } catch (error) {
                that.tipVisible = true;
                that.tipContent = '自由流程设置节点失败，无法进行审批操作！';
                console.log('自由流程设置节点失败 :' + error);
                return false;
            }
        }

        //当前审核分割组，第一组是已经审核通过的，第二组是待审核的
        var auditArray = allAudit.split(',' + curAuditor + ',');
        //如果存在审核人
        var firstAuditor = auditArray[1];

        //如果待审核节点为空，则表示已经审批通过
        if (firstAuditor == '') {
            //流程状态 1：待提交  2：审核中  3：审批中  4：已完成  5：已完成  10：已作废

            //检测当前审批节点是否为最后一个节点，如果是最后一个节点，则将审批状态修改为4：已完成，修改当前审批状态为待处理
            result = await manageAPI.patchTableData(
                tableName,
                curRow['business_data_id'], {
                    bpm_status: '4',
                }
            );

            //执行知会流程，添加多条知会记录。将知会节点的所有待知会节点，拆分成为数组，遍历数组，数组中每个元素，推送一条知会记录，注意forEach不能使用await
            for (let item of notifyArray) {
                //第二步，根据流程业务模块，获取流程审批节点；操作职员，可能有多个，则每个员工推送消息,需要从流程配置节点中获取
                var employee = await manageAPI.queryProcessNodeEmployee(item);
                //流程岗位
                var process_station = await manageAPI.queryProcessNodeProcName(
                    item
                );
                //审批相关流程节点
                var pnode = {};

                if (curRow.business_code != '000000000') {
                    //提交审批相关处理信息
                    pnode = {
                        id: manageAPI.queryRandomStr(32), //获取随机数
                        table_name: tableName, //业务表名
                        main_value: curRow['main_value'], //表主键值
                        business_data_id: curRow['business_data_id'], //业务具体数据主键值
                        business_code: that.fixedWFlow['id'], //业务编号
                        process_name: that.fixedWFlow['items'], //流程名称
                        employee: employee[0]['employee'],
                        process_station: process_station[0]['item_text'],
                        process_audit: item,
                        operate_time: date,
                        create_time: date,
                        proponents: curRow['proponents'],
                        content: curRow['content'],
                        business_data: JSON.stringify(curRow),
                    };
                } else {
                    //提交审批相关处理信息
                    pnode = {
                        id: manageAPI.queryRandomStr(32), //获取随机数
                        table_name: tableName, //业务表名
                        main_value: curRow['business_data_id'], //表主键值
                        business_data_id: curRow['business_data_id'], //业务具体数据主键值
                        business_code: '000000001', //业务编号
                        process_name: '自由流程知会', //流程名称
                        employee: item,
                        process_station: '自由流程知会',
                        process_audit: '000000001',
                        proponents: curRow['proponents'],
                        content: curRow['content'],
                        operate_time: date,
                        create_time: date,
                        business_data: curRow.business_data,
                    };
                }

                //向流程审批日志表PR_LOG和审批处理表BS_APPROVE添加数据 , 并获取审批处理返回信息
                result = await manageAPI.postProcessLogInformed(pnode);
            }

            //当前已经是最后一个审批节点，流程已经处理完毕
            that.tipContent = '同意审批成功，审批流程处理完毕！';
        } else {
            //如果firstAuditor是逗号开头，则去掉开头的逗号
            firstAuditor =
                firstAuditor.indexOf(',') == 0 ?
                firstAuditor.substring(1) :
                firstAuditor;
            //获取下一审核节点
            firstAuditor = firstAuditor.split(',')[0];

            //设置流程状态为2：审核中
            let bpm_status_code = '2';

            //检查当前审核节点是否为审批节点，如果是，则bpm_status_code设置为3：审批中
            if (approveNode == firstAuditor) {
                bpm_status_code = '3';
            }

            //修改审批状态为审批中，并记录审批日志；将当前审批状态修改为处理中 （待提交	1	处理中	2	已完成	3	已作废	4）
            result = await manageAPI.patchTableData(
                tableName,
                curRow['business_data_id'], {
                    bpm_status: bpm_status_code,
                }
            );

            //审批相关处理信息
            var pnode = {};

            if (curRow.business_code != '000000000') {
                //第二步，根据流程业务模块，获取流程审批节点；操作职员，可能有多个，则每个员工推送消息,需要从流程配置节点中获取
                var employee = await manageAPI.queryProcessNodeEmployee(
                    firstAuditor
                );
                //流程岗位
                var process_station = await manageAPI.queryProcessNodeProcName(
                    firstAuditor
                );
                //提交审批相关处理信息
                pnode = {
                    id: manageAPI.queryRandomStr(32), //获取随机数
                    table_name: tableName, //业务表名
                    main_value: curRow['main_value'], //表主键值
                    business_data_id: curRow['business_data_id'], //业务具体数据主键值
                    business_code: that.fixedWFlow['id'], //业务编号
                    process_name: that.fixedWFlow['items'], //流程名称
                    employee: employee[0]['employee'],
                    process_station: process_station[0]['item_text'],
                    process_audit: firstAuditor,
                    proponents: curRow['proponents'],
                    content: curRow['content'],
                    create_time: date,
                    business_data: curRow.business_data,
                };
            } else {
                //提交审批相关处理信息
                pnode = {
                    id: manageAPI.queryRandomStr(32), //获取随机数
                    table_name: tableName, //业务表名
                    main_value: curRow['business_data_id'], //表主键值
                    business_data_id: curRow['business_data_id'], //业务具体数据主键值
                    business_code: '000000000', //业务编号
                    process_name: '自由流程审批', //流程名称
                    employee: firstAuditor,
                    process_station: '自由流程审批',
                    process_audit: '000000000',
                    proponents: curRow['proponents'],
                    content: curRow['content'],
                    operate_time: date,
                    create_time: date,
                    business_data: curRow.business_data,
                };
            }

            //提交审批前，先检测同一业务表名下，是否有同一业务数据主键值，如果存在，则提示用户，此记录，已经提交审批
            let vflag = await manageAPI.queryApprovalLength(
                tableName,
                curRow['business_data_id']
            );

            if (vflag == 0) {
                //数据库中已经存在此记录，提示用户无法提交审批
                that.tipContent = `处理异常，请稍后重试；如果多次处理异常，可能需要撤销当前审批，重新发起审批流程！异常流程数据[status:${vflag}]`;
            } else {
                //根据流程业务模块，获取流程审批节点，如果含有加签，弹出弹框，选择一个加选审批人，如果没有，则直接下一步

                //向流程审批日志表PR_LOG和审批处理表BS_APPROVE添加数据 , 并获取审批处理返回信息
                result = await manageAPI.postProcessLog(pnode);

                //第三步，根据流程审批节点，向第一个节点推送一条审批信息；根据流程审批节点，找到当前审批节点，修改节点审批状态为审批通过，增加审批意见
                console.log(
                    ' 修改当前记录审批状态为处理中返回结果:' + JSON.stringify(result)
                );

                //将当前待审核节点，添加至datasource中
                that.table.dataSource.push(pnode);

                //提示信息
                that.tipContent = '同意审批成功，审批流程已推向后续处理人！';
            }
        }

        //提示用户撤销审批操作成功
        that.tipVisible = true;
    }

    that.loadData();

    console.log('同意审批成功！');

    return '';
}

/**
 * @function 驳回审批
 */
export async function handleRejectWF(that, storage, tools, manageAPI) {

    //返回结果
    let result;
    //获取当前用户
    let userInfo = storage.getStore('cur_user');
    //获取当前时间
    let date = tools.formatDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss');

    //审批动作
    let operation = operation || '驳回';
    //审批意见
    let message = message || '';

    //当前被选中记录数据
    let curRow = that.table.selectionRows[0];

    //检测是否为单选
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }

    //打印表单名称
    let tableName = curRow['table_name'];

    //检查审批权限，当前用户必须属于操作职员中，才可以进行审批操作
    if (!(
            curRow['employee'].includes(userInfo['username']) ||
            curRow['employee'].includes(userInfo['realname'])
        )) {
        that.$message.warning(
            '您不在此审批流程记录的操作职员列中，无法进行驳回操作！'
        );
        return false;
    }

    //获取当前审批节点的所有数据
    curRow = await manageAPI.queryProcessLogByID(tableName, curRow['id']);

    //获取关于此表单的所有当前审批日志信息
    let node = await manageAPI.queryProcessLog(
        tableName,
        curRow['business_data_id']
    );

    //遍历node,设置approve_user，action
    window.__.each(node, (item) => {
        item['approve_user'] = userInfo['username'];
        item['action'] = operation;
        item['operate_time'] = date;
        item['action_opinion'] = message;
    });

    //将当前审批日志转为历史日志，并删除当前审批日志中相关信息
    result = await manageAPI.postProcessLogHistory(node);

    //删除当前审批节点中的所有记录
    result = await manageAPI.deleteProcessLog(tableName, node);

    //修改当前审批状态为待处理
    result = await manageAPI.patchTableData(
        tableName,
        curRow['business_data_id'], {
            bpm_status: '1',
        }
    );
    //再次执行修改流程状态的操作，防止网络异常
    result = await manageAPI.patchTableData(
        tableName,
        curRow['business_data_id'], {
            bpm_status: '1',
        }
    );

    //提示用户撤销审批操作成功
    that.tipVisible = true;
    that.tipContent = '驳回审批成功！';

    that.loadData();
    //打印驳回审批处理日志
    console.log('驳回审批成功');

    //返回结果
    return result;
}

/**
 * @function 提交审批
 */
export async function handleSubmitWF(that, tools, storage, manageAPI) {

    //获取当前变量
    let result = {};

    //获取当前时间
    var date = tools.formatDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss');

    //检查是否存在选择记录
    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }

    //当前被选中记录Index
    let index = that.table.selectedRowKeys[0];
    //当前被选中记录数据
    let curRow = that.table.selectionRows[0];
    //查询是否存在流程，如果存在流程，则不能提交审批
    let exnode = await manageAPI.queryExistWorkflow(curRow.id);

    //打印index序号
    console.log('index: ' + index);

    //已经提交审批，无法再次提交
    if (
        curRow['bpm_status'] == '2' ||
        curRow['bpm_status'] == '3' ||
        (typeof exnode != 'undefined' && exnode != null)
    ) {
        that.tipVisible = true;
        that.tipContent = '待审记录中，已经存在此记录，无法再次提交审批！';
        return false;
    } else if (curRow['bpm_status'] == '4' || curRow['bpm_status'] == '5') {
        that.tipVisible = true;
        that.tipContent = '此记录的审批流程，已经完成审批，无法再次提交审批！';
        return false;
    } else if (curRow['bpm_status'] == '10') {
        that.tipVisible = true;
        that.tipContent = '此记录的审批流程，已经作废，无法再次提交审批！';
        return false;
    }

    //获取当前用户信息
    let userInfo = storage.getStore('cur_user');

    //检查审批权限，当前用户必须申请人员，才可以进行提交审批操作

    //第一步，获取此表单，关联的流程业务模块
    let value = await manageAPI.queryTableName();

    //打印表单名称
    let tableName = value['table_name'];

    //打印表单信息
    console.log(' tableName : ' + value['table_name'] + ' 执行提交审批操作')

    //TODO 获取是否存在待审批处理的日志记录

    //TODO 如果审批状态是待提交，但是存在待处理的审批日志的，则修改状态为审批中，且提示，已经提交审批，无法再次提交审批

    //查询SQL , 获取流程权责中关联业务含有tableName的流程权责
    let rights = await manageAPI.queryBusinessInfo(tableName);

    //选定流程权责
    that.fixedWFlow = rights[0];
    that.rights = rights;

    //如果流程权责有多个，那么弹出选择框，让用户自己选择一个流程
    if (rights.length > 1) {
        that.modelModal = true;
        return false;
    } else if (rights.length <= 0) {
        that.tipVisible = true;
        that.tipContent = '尚未配置此业务的流程权责，无法提交审批！';
        return false;
    } else {
        //如果存在审核人
        var firstAuditor = that.fixedWFlow['audit'].split(',')[0];
        //操作职员，可能有多个，则每个员工推送消息,需要从流程配置节点中获取
        var employee = await manageAPI.queryProcessNodeEmployee(firstAuditor);
        //流程岗位
        var process_station = await manageAPI.queryProcessNodeProcName(
            firstAuditor
        );

        //没有获取到审核节点的用户信息，请在流程设计->节点配置中设置审核节点的审核用户
        if (Array.isArray(employee) && employee.length == 0) {
            this.$notification['error']({
                message: '温馨提示',
                description: '没有获取到审核节点的用户信息，请在流程设计->节点配置中设置审核节点的审核用户！',
                duration: 4,
            });
            return false;
        }

        //提交审批相关处理信息
        var node = {
            id: manageAPI.queryRandomStr(32), //获取随机数
            table_name: tableName, //业务表名
            main_value: value['id'], //表主键值
            business_data_id: curRow['id'], //业务具体数据主键值
            business_code: that.fixedWFlow['id'], //业务编号
            process_name: that.fixedWFlow['items'], //流程名称
            employee: employee[0]['employee'],
            process_station: process_station[0]['item_text'],
            process_audit: firstAuditor,
            proponents: userInfo['realname'],
            content: curRow['content'],
            create_time: date,
            business_data: JSON.stringify(curRow),
        };

        //提交审批前，先检测同一业务表名下，是否有同一业务数据主键值，如果存在，则提示用户，此记录，已经提交审批
        let vflag = await manageAPI.queryApprovalExist(tableName, curRow['id']);

        if (vflag) {
            //数据库中已经存在此记录，提示用户无法提交审批

            that.tipContent = '待审记录中，已经存在此记录，无法再次提交审批！';
        } else {
            //第二步，根据流程业务模块，获取流程审批节点，如果含有加签，弹出弹框，选择一个加选审批人，如果没有，则直接下一步

            var firstNode = {
                id: manageAPI.queryRandomStr(32), //获取随机数
                table_name: tableName, //业务表名
                main_value: value['id'], //表主键值
                business_data_id: curRow['id'], //业务具体数据主键值
                business_code: that.fixedWFlow['id'], //业务编号
                process_name: that.fixedWFlow['items'], //流程名称
                employee: userInfo['username'],
                process_station: process_station[0]['item_text'],
                process_audit: '000000003',
                proponents: userInfo['username'],
                approve_user: userInfo['username'],
                action: '发起',
                action_opinion: '发起固化流程',
                content: curRow['content'],
                operate_time: date,
                create_time: date,
                business_data: JSON.stringify(curRow),
            };

            //向流程审批日志表PR_LOG和审批处理表BS_APPROVE添加数据 , 并获取审批处理返回信息
            result = await manageAPI.postProcessLogHistory(firstNode);

            //向流程审批日志表PR_LOG和审批处理表BS_APPROVE添加数据 , 并获取审批处理返回信息
            result = await manageAPI.postProcessLog(node);

            //打印提交审批返回结果
            console.log(' 提交审批返回结果: ' + JSON.stringify(result));

            //第三步，根据流程审批节点，向第一个节点推送一条审批信息

            //第四步，修改审批状态为审批中，并记录审批日志；将当前审批状态修改为处理中 （���提交	1	处理中	2	已完成	3	已作废	4）
            result = await manageAPI.patchTableData(tableName, curRow['id'], {
                bpm_status: '2',
            });
            //再次执行一次修改流程状态的操作，防止网络异常
            result = await manageAPI.patchTableData(tableName, curRow['id'], {
                bpm_status: '2',
            });

            //设置流程状态为审核中
            curRow['bpm_status'] = '2';

            //打印审批日志信息
            let logging =
                ' 修改当前记录审批状态为处理中返回结果:' + JSON.stringify(result);
            console.log(logging);

            //提示审批提交成功
            that.tipContent = '提交审批成功！';
        }

        //弹出审批完成提示框
        that.tipVisible = true;

        //刷新页面
        that.loadData();

        //打印获取到的流程权责信息
        console.log(
            ' tableName : ' + tableName + ' \n rights : ' + JSON.stringify(rights)
        );

        //返回处理结果
        return true;
    }
}

/**
 * @function 取消审批函数
 */
export async function handleCancelWF(that, storage, tools, manageAPI, workflowAPI) {

    //返回结果
    let result;
    //获取当前用户
    let userInfo = storage.getStore('cur_user');
    //获取当前时间
    let date = tools.formatDate(new Date().getTime(), 'yyyy-MM-dd hh:mm:ss');

    //审批动作
    let operation = '撤销';
    //审批意见
    let message = '撤销审批';

    //当前被选中记录数据
    let curRow = that.table.selectionRows[0];

    if (that.table.selectionRows.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    }

    //第一步，获取此表单，关联的流程业务模块
    let value = await manageAPI.queryTableName();

    //打印表单名称
    let tableName = value['table_name'];

    //已经提交审批，无法再次提交；或者：如果流程状态是未提交，则可以撤销审批，因为有时，进入流程状态，且有审批日志，但是出现Bug导致状态为未提交，则也应该可以撤销审批
    if (curRow['bpm_status'] == '1') {
        that.tipVisible = true;
        that.tipContent = "该记录尚未提交审批！";
        //return false;
    } else if (curRow['bpm_status'] == '4' || curRow['bpm_status'] == '5') {
        that.tipVisible = true;
        that.tipContent = '该记录已完成审批，无法撤销审批！';
        return false;
    } else if (curRow['bpm_status'] == '10') {
        that.tipVisible = true;
        that.tipContent = '该记录审批流程已作废，无法撤销审批！';
        return false;
    }

    //获取关于此表单的所有当前审批日志信息
    let node = await manageAPI.queryProcessLog(tableName, curRow['id']);

    //检查审批权限，当前用户必须申请人员，才可以进行撤销审批操作

    //遍历node,设置approve_user，action
    window.__.each(node, function(item) {
        //记录创建时间
        let ctime = item['create_time'];
        //设置审批人员
        item['approve_user'] = userInfo['username'];
        //设置操作类型
        item['action'] = operation;
        //设置操作时间
        item['operate_time'] = date;
        //设置操作意见
        item['action_opinion'] = message;
        //设置创建时间
        item['create_time'] = tools.formatDate(ctime, 'yyyy-MM-dd hh:mm:ss');
    });

    //执行撤销流程
    workflowAPI.postWorkflowCancel(tableName, curRow, node);

    //设置当前表单中的审批状态为待处理
    curRow['bpm_status'] = '1';

    //提示用户撤销审批操作成功
    that.tipVisible = true;
    that.tipContent = '撤销审批成功！';

    //加载数据
    that.loadData();

    //设置返回结果
    return result;
}

/**
 * @function 处理导出Excel函数
 */
export function handleExportXls2(that) {
    //获取导出参数
    let param = that.queryParam;

    //检查导出数据
    if (that.table.selectionRows.length <= 0) {
        that.$message.warning('请选择需要导出的记录！');
        return false;
    }

    //设置导出数据
    if (that.table.selectedRowKeys && that.table.selectedRowKeys.length > 0) {
        param['selections'] = that.table.selectedRowKeys.join(',');
    }

    let paramsStr = encodeURI(JSON.stringify(param));
    console.log('paramsStr: ' + paramsStr);
    let url =
        window._CONFIG['domainURL'] +
        that.url.exportXls +
        that.code +
        '?paramsStr=' +
        paramsStr;
    window.location.href = url;
}

/**
 * @function 处理导出Excel函数
 */
export function handleExportXls(that, storage, tools, manageAPI) {
    //定义导出参数
    let param = that.queryParam;

    //获取当前用户
    var userInfo = storage.getStore('cur_user');

    //检查导出数据
    if (that.table.selectionRows.length <= 0) {
        that.$message.warning('请选择需要导出的记录！');
        return false;
    }

    //设置导出数据
    if (that.table.selectedRowKeys && that.table.selectedRowKeys.length > 0) {
        param['selections'] = that.table.selectedRowKeys.join(',');
    }

    //参数序列化
    let paramsStr = JSON.stringify(tools.filterObj(param));

    //执行下载请求
    manageAPI
        .downFile(that.url.exportXls + that.code, { paramsStr: paramsStr })
        .then((data) => {
            if (!data) {
                that.$message.warning('文件下载失败');
                return;
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                window.navigator.msSaveBlob(
                    new Blob([data]),
                    `${that.description}_${userInfo.realname}.xls`
                );
            } else {
                let url = window.URL.createObjectURL(new Blob([data]));
                let link = document.createElement('a');
                link.style.display = 'none';
                link.href = url;
                link.setAttribute(
                    'download',
                    `${this.description}_${userInfo.realname}.xls`
                );
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); //下载完成移除元素
                window.URL.revokeObjectURL(url); //释放掉blob对象
            }
        });

    //打印参数信息
    console.log('导出参数', param);
}

/**
 * @function 执行删除操作
 */
export function handleDelete(that, id, manageAPI) {
    manageAPI
        .deleteAction(that.url.optPre + that.code + '/' + id)
        .then((res) => {
            if (res.success) {
                that.$message.success(res.message);
                that.loadData();
            } else {
                that.$message.warning(res.message);
            }
        });
}

/**
 * @function 下载文件函数
 */
export function uploadFile(that, text) {
    if (!text) {
        that.$message.warning('未知的文件');
    } else {
        window.open(window._CONFIG['downloadURL'] + '/' + that.queryFirstFile(text));
    }
}

/**
 * @function 预览文档函数
 */
export function viewFile(that, text) {

    if (!text) {
        that.$message.warning('未知的文件');
    } else {
        //获取第一个文件路径
        text = that.queryFirstFile(text);

        //微软文档预览API
        let officeURL = 'https://view.officeapps.live.com/op/view.aspx?src=';

        //IDOCV文档预览API
        let idocvURL = window._CONFIG['viewURL'];

        //文档下载地址
        let url = window._CONFIG['downloadURL'] + '/' + text;

        //URL加密，保证中文路径可以被正常解析
        let xurl = encodeURIComponent(url);

        //获取文件后缀
        let suffix = text
            .substring(text.lastIndexOf('.'), text.length)
            .toLowerCase();

        //如果word文档，则使用微软API打开
        url =
            suffix.includes('doc') ||
            suffix.includes('ppt') ||
            suffix.includes('xls') ?
            officeURL + xurl :
            idocvURL + url;

        //如果pdf文档，则浏览器上直接打开
        url = suffix.includes('pdf') ? url : url;

        //浏览器打开预览
        window.open(url);
    }
}

/**
 * @function 处理删除选中记录函数
 */
export function handleDelBatch(that) {
    //处理删除选中记录函数
    if (that.table.selectedRowKeys.length != 1) {
        that.$message.warning('请选择一条记录！');
        return false;
    } else {
        //待删除ID值数组
        let ids = '';
        //当前被选中记录数据
        let curRow = that.table.selectionRows[0];
        //已经提交审批，无法再次提交
        if (curRow['bpm_status'] != '1') {
            that.$message.warning('当前记录已经进入流程，无法删除！');
            return false;
        }
        //获取所有勾选的记录
        that.table.selectedRowKeys.forEach(function(val) {
            ids += val + ',';
        });
        //点击确认删除，执行删除操作
        that.$confirm_({
            title: '确认删除',
            content: '是否删除选中数据?',
            onOk: function() {
                that.handleDelete(ids);
                that.onClearSelected();
            },
        });
    }
}

/**
 * @function 格式化日期
 * @param {*} text 
 */
export function getFormatDate(text) {
    if (!text) {
        return '';
    } else {
        let a = text;
        if (a.length > 10) {
            a = a.substring(0, 10);
        }
        return a;
    }
}

/**
 * @function 初始化EnhanceJs函数
 * @param {*} enhanceJs 
 * @param {*} that 
 * @param {*} manageAPI 
 */
export function initCgEnhanceJs(enhanceJs, that, manageAPI) {
    if (enhanceJs) {
        let Obj = eval('(' + enhanceJs + ')');
        that.EnhanceJS = new Obj(
            manageAPI.getAction,
            manageAPI.postAction,
            manageAPI.deleteAction
        );
        that.cgButtonJsHandler('created');
    } else {
        that.EnhanceJS = '';
    }
}

/**
 * @function 初始化自定义按钮函数
 * @param {*} btnList 
 * @param {*} that 
 */
export function initCgButtonList(btnList, that) {
    let linkArr = [];
    let buttonArr = [];
    if (btnList && btnList.length > 0) {
        for (let i = 0; i < btnList.length; i++) {
            let temp = btnList[i];
            if (temp.buttonStyle == 'button') {
                buttonArr.push(temp);
            } else if (temp.buttonStyle == 'link') {
                linkArr.push(temp);
            }
        }
    }
    that.cgButtonLinkList = [...linkArr];
    that.cgButtonList = [...buttonArr];
}

/**
 * @function 自定义按钮处理函数
 * @param {*} buttonCode 
 * @param {*} that 
 */
export function cgButtonJsHandler(buttonCode, that) {
    if (that.EnhanceJS[buttonCode]) {
        that.EnhanceJS[buttonCode](that);
    }
}

/**
 * @function 自定义按钮执行操作函数
 * @param {*} buttonCode 
 * @param {*} that 
 * @param {*} manageAPI 
 */
export function cgButtonActionHandler(buttonCode, that, manageAPI) {
    //处理自定义button的 需要配置该button自定义sql
    if (!that.table.selectedRowKeys ||
        that.table.selectedRowKeys.length == 0
    ) {
        that.$message.warning('请先选中一条记录');
        return false;
    }
    if (that.table.selectedRowKeys.length > 1) {
        that.$message.warning('请只选中一条记录');
        return false;
    }
    let params = {
        formId: that.code,
        buttonCode: buttonCode,
        dataId: that.table.selectedRowKeys[0],
    };
    console.log('自定义按钮请求后台参数：', params);
    manageAPI.postAction(that.url.buttonAction, params).then((res) => {
        if (res.success) {
            that.loadData();
            that.$message.success('处理完成!');
        } else {
            that.$message.warning('处理失败!');
        }
    });
}

/**
 * @function 自定义按钮执行链接处理函数
 * @param {*} record 
 * @param {*} buttonCode 
 * @param {*} optType 
 * @param {*} that 
 * @param {*} manageAPI 
 */
export function cgButtonLinkHandler(record, buttonCode, optType, that, manageAPI) {
    if (optType == 'js') {
        if (that.EnhanceJS[buttonCode]) {
            that.EnhanceJS[buttonCode](that, record);
        }
    } else if (optType == 'action') {
        let params = {
            formId: that.code,
            buttonCode: buttonCode,
            dataId: record.id,
        };
        console.log('自定义按钮link请求后台参数：', params);
        manageAPI.postAction(that.url.buttonAction, params).then((res) => {
            if (res.success) {
                that.loadData();
                that.$message.success('处理完成!');
            } else {
                that.$message.warning('处理失败!');
            }
        });
    }
}

/**
 * @function 初始化按钮切换函数
 * @param {*} hideColumns 
 * @param {*} that 
 */
export function initButtonSwitch(hideColumns, that) {
    if (hideColumns && hideColumns.length > 0) {
        Object.keys(that.buttonSwitch).forEach((key) => {
            if (hideColumns.indexOf(key) >= 0) {
                that.buttonSwitch[key] = false;
            }
        });
    }
}